import jwt
import datetime
from django.conf import settings
from django.core.serializers import serialize
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.base.serializers.account import AuthSerializer
from utils import return_code
from apps.base import models



class AuthView(APIView):
    authentication_classes = []
    permission_classes = []
    def post(self, request,*args,**kwargs):
        # print(request.user)
        # print(request.auth)
    # 1.获取用户请求发送的用户名&密码
        serialize=AuthSerializer(data=request.data)
    # 2.数据校验
        if not serialize.is_valid():
            return Response({'code':return_code.FIELD_ERROR,'detail':serialize.errors})
    # 3.数据库校验
        username=serialize.validated_data.get('username')
        password=serialize.validated_data.get('password')
        user_obj=models.UserInfo.objects.filter(username=username,password=password).first()
        if not user_obj:
            return Response({'code':return_code.VALIDATA_ERROR,'detail':'用户名或密码错误'})
    # 4.生成jwt token返回
        headers={
            'typ':'JWT',
            'alg':'HS256',
        }
        payload={
            'user_id':user_obj.id,
            'username':user_obj.username,
            'exp':datetime.datetime.now()+datetime.timedelta(days=7),
        }
        token=jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256',headers=headers)
        print(token)

        return Response({'code':return_code.SUCCESS,'data':{'username':username,'token':token}})

class TestView(APIView):
    def get(self,request,*args,**kwargs):
        print(request.user.user_id)
        print(request.user.username)
        print(request.user.exp)
        return Response("test...")
